### Avoid for loops with purrr
### Simulate With Purrr map & map2
require(tidyverse)
### Mean and SD from two groups ==> HRT and Placebo
### Within each group we have two measurements, HDL and LDL
d <- tibble(group = c("HRT", "Placebo"),
MeanHDL = c(8.1, 2.4),
sdHDL = c(10.5, 4.3),
MeanLDL = c(-18.2, -2.2),
sdLDL = c(26.5, 12.2))
d
## # A tibble: 2 x 5
## group MeanHDL sdHDL MeanLDL sdLDL
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 HRT 8.1 10.5 -18.2 26.5
## 2 Placebo 2.4 4.3 -2.2 12.2
### For vertical lines in ggplot
vline.data <- data.frame(z = c(8.1, 2.4, -18.2, -2.2),
Type = c("SimHDL", "SimHDL", "SimLDL", "SimLDL"))
vline.data
## z Type
## 1 8.1 SimHDL
## 2 2.4 SimHDL
## 3 -18.2 SimLDL
## 4 -2.2 SimLDL
### Simulate
dsim <- d %>%
mutate(SimHDL = map2(MeanHDL, sdHDL, ~ rnorm(10000, ..1, ..2)),
SimLDL = map2(MeanLDL, sdLDL, ~ rnorm(10000, ..1, ..2))
)
### purrr just enabled me to avoid writing TWO for loops
dsim
## # A tibble: 2 x 7
## group MeanHDL sdHDL MeanLDL sdLDL SimHDL SimLDL
## <chr> <dbl> <dbl> <dbl> <dbl> <list> <list>
## 1 HRT 8.1 10.5 -18.2 26.5 <dbl [10,000]> <dbl [10,000]>
## 2 Placebo 2.4 4.3 -2.2 12.2 <dbl [10,000]> <dbl [10,000]>
head(dsim %>%
unnest(cols = SimHDL:SimLDL)
)
## # A tibble: 6 x 7
## group MeanHDL sdHDL MeanLDL sdLDL SimHDL SimLDL
## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 HRT 8.1 10.5 -18.2 26.5 -1.14 -8.39
## 2 HRT 8.1 10.5 -18.2 26.5 13.0 -40.9
## 3 HRT 8.1 10.5 -18.2 26.5 17.0 -30.1
## 4 HRT 8.1 10.5 -18.2 26.5 13.6 -13.1
## 5 HRT 8.1 10.5 -18.2 26.5 3.14 -31.9
## 6 HRT 8.1 10.5 -18.2 26.5 -1.75 16.2
### Make Plot
plotly::ggplotly(
dsim %>%
pivot_longer(cols = SimHDL:SimLDL,names_to = "Type", values_to = "Value") %>%
unnest() %>%
ggplot(aes(Value, fill = group, color = group)) +
geom_density(alpha = 0.3) +
geom_vline(data = vline.data, aes(xintercept = z), alpha = 0.5, linetype = "longdash")+
facet_wrap(~Type, scales = "free") +
theme_light()
)

References
Weiss, NA. 2005. “Introductory Statistics.” Pearson Education, Inc.